#encoding:utf8
#file:views.py
#@author:carlos
#@date:2011-2-13
#@link:tieniuzai.com
from django import template
from django.http import  HttpRequest
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
import os, sys
from sinatpy.weibopy.auth import OAuthHandler
from sinatpy.weibopy.api import API
import base64

def reponse_weibo(request):
    """
    请求新浪微博，返回新浪微博地址
    """
    back_to_url = _get_referer_url(request)
    login_backurl = request.build_absolute_uri('/')
    if 'Ticket' in request.GET:
        request.session["backurl"] = back_to_url + base64.b64encode(request.GET['Ticket'])
    else:
        request.session["backurl"] = back_to_url
    auth = OAuthHandler("1427215379","23906bef593fd90cb4ce6354c6bf83f3",callback="http://127.0.0.1:8000/Login/weibo")
    auth_url = auth.get_authorization_url()

   # print 'Please authorize: ' + auth_url
    #verifier = input('PIN: ')#.strip()
    #access_token= auth.get_access_token()
    request.session['outh']=auth
    return  HttpResponseRedirect(auth_url)
    #result= request.POST["oauth_verifier"]

def weibo(request):
    """
    新浪验证成功之后请求的地址
    """    
    verifier = request.GET.get('oauth_verifier', None)
    print (verifier)
    auth= request.session['outh']
    access_token= auth.get_access_token(verifier)
    request.session["token"]=access_token
   # request.session['outh']=auth
    # access_token= auth.get_access_token(verifier)
    #print (access_token.secret)
    #print (access_token.key)
    #api = API(auth)
    #auth.setToken(access_token.key, access_token.secret)
    #api = API(auth)
    username=auth.get_username()
    request.session['username'] = username
    #message = u"。。。。。。"+username
    #message=message.encode("utf-8")
    #status = api.update_status(status=message, lat="30", long="110")
    #username=auth.get_username()
    return HttpResponseRedirect(request.session["backurl"])
def SendOut(request):
    """
    发送微博信息
    """
    auth= request.session['outh']
    message = request.GET.get("message",None)
    access_token= request.session["token"]
    api = API(auth)
    auth.setToken(access_token.key, access_token.secret)
    message=message.encode("utf-8")
    status = api.update_status(status=message, lat="30", long="110")
def _get_referer_url(request):
    referer_url = request.META.get('HTTP_REFERER', '/')
    host = request.META['HTTP_HOST']
    if referer_url.startswith('http') and host not in referer_url:
        referer_url = '/' # 避免外站直接跳到登录页而发生跳转错误
    return referer_url

def Exit(request):
    request.session.flush()
    return HttpResponseRedirect(request.build_absolute_uri('/'))